package com.qianbao.qianbaobusiness.ui.qrcode;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.dialog.LoadingDialog;
import com.androidbase.utils.DisplayUtils;
import com.androidbase.utils.RxUtils;
import com.androidbase.utils.ToastUtils;
import com.baseandroid.config.Global;
import com.baseandroid.event.QrCodeShopSwitchEvent;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.retrofit.RxObserver;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.MerchantQrCodeBean;
import com.qianbao.qianbaobusiness.json.QrBean;
import com.qianbao.qianbaobusiness.ui.mine.qrcode.ApplyQrCardActivity;
import com.qianbao.qianbaobusiness.ui.qrcode.adapter.QrAdapter;
import com.qianbao.qianbaobusiness.ui.zxing.ZXingScanActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class BindQrCodeActivity extends BaseMvpActivity<BindQrCodeView, BindQrCodePresenter> implements BindQrCodeView {
    @BindView(R.id.list_qr)
    RecyclerView   mRv;
    @BindView(R.id.toolbar_title)
    TextView       toolbar_title;
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbar_back;
    @BindView(R.id.right_text)
    TextView       mTvRightText;
    @BindView(R.id.shop_name)
    TextView       tvShopName;
    @BindView(R.id.lin_shop_name)
    LinearLayout   mLlShopPick;
    @BindView(R.id.fl_bind)
    FrameLayout    mFlBind;
    QrAdapter adapter;

    private LoadingDialog mUpdateProgressDialog;
    private String mDownLoadApkFolde = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                                               .getAbsolutePath();
    private String       mDownLoadApkFileName;
    private String       mUrl;
    private MerchantInfo mSelectedMerchant;
    private boolean      mShowGuide;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bind_qr_code;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        mShowGuide = getIntent().getBooleanExtra("showGuide", false);
        EventBus.getDefault().register(this);
        initView();
    }

    private void showGuideView() {
        FrameLayout rootView = findViewById(android.R.id.content);
        RelativeLayout helpView = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.layout_guide_qrcode_bind_jinjian_step2, null);
        helpView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        ViewTreeObserver viewTreeObserver = mTvRightText.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (viewTreeObserver.isAlive()) {
                    viewTreeObserver.removeOnGlobalLayoutListener(this);
                }
                Rect rect = new Rect();
                TextView tvApply = helpView.findViewById(R.id.tv_apply);
                mTvRightText.getGlobalVisibleRect(rect);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tvApply.getLayoutParams();
                lp.setMargins(0, DisplayUtils.dp2px(5) + rect.top, DisplayUtils.dp2px(5), 0);
                tvApply.setLayoutParams(lp);
                helpView.findViewById(R.id.iv_confirm1).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        helpView.findViewById(R.id.fl_bind).setVisibility(View.VISIBLE);
                        helpView.findViewById(R.id.iv_confirm2).setVisibility(View.VISIBLE);
                        helpView.findViewById(R.id.iv_guide2).setVisibility(View.VISIBLE);
                        helpView.findViewById(R.id.tv_apply).setVisibility(View.GONE);
                        helpView.findViewById(R.id.iv_guide1).setVisibility(View.GONE);
                        helpView.findViewById(R.id.iv_confirm1).setVisibility(View.GONE);
                    }
                });
                helpView.findViewById(R.id.iv_confirm2).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rootView.removeView(helpView);
                    }
                });
            }
        });
        rootView.addView(helpView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(QrCodeShopSwitchEvent event) {
        Global.setQrCardSelectedMerchantNo(event.getMerchantNo());
        initData();
    }

    private void initView() {
        toolbar_title.setText("二维码绑定");
        mTvRightText.setText("申请收款码");
        mTvRightText.setTextColor(ContextCompat.getColor(this, R.color.text_support));
        mTvRightText.setVisibility(View.VISIBLE);
        adapter = new QrAdapter(this);
        mRv.setLayoutManager(new GridLayoutManager(this, 2));
        mRv.setAdapter(adapter);
        adapter.setEmptyView(R.layout.layout_empty_bind_qrcode);
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        initData();
    }

    private void initData() {
        if (TextUtils.isEmpty(Global.getQrCardSelectedMerchantNo())) {
            if (Global.getShopListInfo().merchantList.size() > 0) {
                mSelectedMerchant = Global.getShopListInfo().merchantList.get(0);
                Global.setQrCardSelectedMerchantNo(mSelectedMerchant.merchantNo);
            } else {
                ToastUtils.showLongToast("暂无门店");
                getWindow().getDecorView().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            }
        } else {
            for (int i = 0; i < Global.getShopListInfo().merchantList.size(); i++) {
                if (Global.getShopListInfo().merchantList.get(i).merchantNo.equals(Global.getQrCardSelectedMerchantNo())) {
                    mSelectedMerchant = Global.getShopListInfo().merchantList.get(i);
                    Global.setQrCardSelectedMerchantNo(mSelectedMerchant.merchantNo);
                    break;
                }
            }
            if (mSelectedMerchant == null) {
                mSelectedMerchant = Global.getShopListInfo().merchantList.get(0);
                Global.setQrCardSelectedMerchantNo(mSelectedMerchant.merchantNo);
            }
        }
        if (Global.getShopListInfo().merchantList.size() <= 1) {
            mLlShopPick.setVisibility(View.GONE);
        }
        tvShopName.setText(TextUtils.isEmpty(mSelectedMerchant.merchantName) ? "" : mSelectedMerchant.merchantName);
        getQrCodeList();
    }

    private void getQrCodeList() {
        getPresenter().findMerchantQrcodeList(mSelectedMerchant.posMerchantNo, mSelectedMerchant.merchantNo);
    }

    @OnClick({R.id.toolbar_back, R.id.fl_bind, R.id.right_text, R.id.lin_shop_name})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.fl_bind:
                IntentIntegrator intentIntegrator = new IntentIntegrator(this);
                // ZXing Android Embedded库提供的扫码Activity默认是横屏的,需要自定义
                intentIntegrator.setCaptureActivity(ZXingScanActivity.class);
                //该方法用于设置“被扫描的二维码图片”可以保存在本地,intent返回
                //intentIntegrator.setBarcodeImageEnabled(false);
                //该方法传0将会使用后置摄像头，传1将会使用前置摄像头
                //intentIntegrator.setCameraId(0);
                //如果设置可以使用QR_CODE_TYPES和ALL_CODE_TYPES
                intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
                //功能是用来调整扫描界面方向的
                intentIntegrator.setOrientationLocked(false);
                //设置扫描界面的提示信息
                //intentIntegrator.setPrompt("这里是二维码扫描界面");
                intentIntegrator.initiateScan();
                break;
            case R.id.right_text:
                Intent intent = new Intent(this, ApplyQrCardActivity.class);
                intent.putExtra("mSelectedMerchant", mSelectedMerchant);
                startActivity(intent);
                break;

            case R.id.lin_shop_name:
                Intent shopSelectIntent = new Intent(this, SwitchShopOfQrActivity.class);
                startActivity(shopSelectIntent);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null && result.getContents() != null) {
                getPresenter().merchantQrcodeBind(mSelectedMerchant.merchantNo, result.getContents());
                return;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void startDownLoad(String url, String name, String qrcode) {
        new RxPermissions((Activity) getMvpView()).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .compose(RxUtils.applySchedulersLifeCycle(getMvpView()))
                .subscribe(new RxObserver<Boolean>() {
                    @Override
                    public void onComplete() {
                        mUrl = url;
                        mDownLoadApkFileName = name;
                        mUpdateProgressDialog = new LoadingDialog();
                        mUpdateProgressDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                                getPresenter().requestDownload(mUrl, mDownLoadApkFolde, mDownLoadApkFileName, qrcode, mSelectedMerchant.merchantNo);
                                mUpdateProgressDialog.getDialog()
                                        .setCanceledOnTouchOutside(false);
                            }
                        });
                        mUpdateProgressDialog.show(getSupportFragmentManager(), "updateprogressdialog");
                    }
                });
    }

    @Override
    public void downloadProgress(int progress) {
    }

    @Override
    public void downloadCompleted() {
        if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
            mUpdateProgressDialog.dismiss();
        }
        File out = new File(mDownLoadApkFolde, mDownLoadApkFileName);
        try {
            MediaStore.Images.Media.insertImage(this.getContentResolver(), out.getAbsolutePath(), mDownLoadApkFileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(this, getPackageName() + "" + ".fileprovider", out);
        } else {
            uri = Uri.fromFile(out);
        }
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    out.getAbsolutePath(), mDownLoadApkFileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        SaveCompleteActivity.start(this, mUrl);
    }

    @Override
    public void downloadFailed() {
        ToastUtils.showLongToast(R.string.start_file_download_error);
        if (mUpdateProgressDialog != null && mUpdateProgressDialog.isVisible()) {
            mUpdateProgressDialog.dismiss();
        }
    }

    @Override
    public void updateUI(MerchantQrCodeBean merchantQrCodeBean) {
        adapter.resetData(merchantQrCodeBean.codes);
        if (merchantQrCodeBean.enableScanCode) {
            mFlBind.setVisibility(View.VISIBLE);
            mTvRightText.setVisibility(View.VISIBLE);
            if (mShowGuide) {
                showGuideView();
            }
        } else {
            mFlBind.setVisibility(View.GONE);
            mTvRightText.setVisibility(View.GONE);
        }
    }

    @Override
    public void updateUrl(String url) {
        mUrl = url;
    }

    @Override
    public void notifyAdapter(QrBean bean) {
        List<QrBean> data = adapter.getData();
        boolean remove = data.remove(bean);
        if (remove) {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void bindQrCodeSuccess() {
        getQrCodeList();
    }

    public void merchantQrcodeRemoveBind(QrBean bean) {
        getPresenter().merchantQrcodeRemoveBind(bean);
    }
}